package com.cqjtu.tto.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqjtu.tto.dao.mapper.DepartmentMapper;
import com.cqjtu.tto.dao.mapper.SysUserMapper;
import com.cqjtu.tto.dao.pojo.Department;
import com.cqjtu.tto.dao.pojo.SysUser;
import com.cqjtu.tto.service.DepartmentService;
import com.cqjtu.tto.vo.DepartmentDataExcel;
import com.cqjtu.tto.vo.DepartmentVo;
import com.cqjtu.tto.vo.ErrorCode;
import com.cqjtu.tto.vo.Results;
import com.cqjtu.tto.vo.params.DepartmentParam;
import com.cqjtu.tto.vo.params.UpdateDepartmentParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author：monkey-L
 * @description:
 * @date: 17:27 2021/12/11
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    @Override
    @Transactional
    public Results departmentAdd(DepartmentParam departmentParam) {
        LambdaQueryWrapper<Department> departmentWrapper = new LambdaQueryWrapper<>();
        departmentWrapper.eq(Department::getDepartmentName,departmentParam.getDepartmentName())
                                .last("limit 1");
        Department department1 = departmentMapper.selectOne(departmentWrapper);
        if (department1 != null) {
            return Results.fail(ErrorCode.DEPARTMENT_EXIST.getCode(),ErrorCode.DEPARTMENT_EXIST.getMsg());
        }
        Department department = new Department();
        BeanUtils.copyProperties(departmentParam,department);
        department.setDepartmentId(System.currentTimeMillis());
        department.setDepartmentResponsibleContent(departmentParam.getDepartmentResponsibleContent());
        department.setDepartmentDeleted(0);
        departmentMapper.insert(department);
        return Results.success("添加部门成功！");
    }

    @Override
    @Transactional
    public Results departmentDelete(String departmentName) {
        LambdaQueryWrapper<Department> departmentWrapper = new LambdaQueryWrapper<>();
        departmentWrapper.eq(Department::getDepartmentName,departmentName)
                .last("limit 1");
        Department department1 = departmentMapper.selectOne(departmentWrapper);
        if (department1 == null) {
            return Results.fail(ErrorCode.DEPARTMENT_NOT_EXIST.getCode(),ErrorCode.DEPARTMENT_NOT_EXIST.getMsg());
        }
        department1.setDepartmentDeleted(1);
        LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
        List<SysUser> sysUsers = sysUserMapper.selectList(sysUserWrapper);
        for (SysUser sysUser : sysUsers) {
            if (sysUser.getDepartmentId().equals(department1.getDepartmentId())) {
                return Results.fail(1030,"该部门包含员工，不能删除，请你先清除该部门员工后尝试！");
            }
        }
        LambdaQueryWrapper<Department> departmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        departmentLambdaQueryWrapper.eq(Department::getDepartmentId,department1.getDepartmentId());

        departmentMapper.delete(departmentLambdaQueryWrapper);
        return Results.success("删除成功！");
    }

    @Override
    @Transactional
    public Results departmentUpdate(UpdateDepartmentParam  departmentParam) {
        LambdaQueryWrapper<Department> departmentWrapper = new LambdaQueryWrapper<>();
        departmentWrapper.eq(Department::getDepartmentName,departmentParam.getOldDepartmentName())
                .last("limit 1");
        Department department1 = departmentMapper.selectOne(departmentWrapper);
        if (department1 == null) {
            return Results.fail(ErrorCode.DEPARTMENT_NOT_EXIST.getCode(),ErrorCode.DEPARTMENT_NOT_EXIST.getMsg());
        }
        Department department = new Department();
        BeanUtils.copyProperties(departmentParam,department);
        department.setDepartmentId(department1.getDepartmentId());
        department.setDepartmentDeleted(0);
        Map<String, Object> map = new HashMap<>();
        map.put("departmentId",department.getDepartmentId());
//        departmentMapper.update();
        LambdaQueryWrapper<Department> departmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        departmentLambdaQueryWrapper.eq(Department::getDepartmentId,department.getDepartmentId());
        departmentMapper.update(department,departmentLambdaQueryWrapper);
//        departmentMapper.update()
        return Results.success("更新部门信息成功！");
    }

    @Override
    @Transactional
    public Results departmentSelectOne(String departmentName) {
        LambdaQueryWrapper<Department> departmentWrapper = new LambdaQueryWrapper<>();
        departmentWrapper.eq(Department::getDepartmentName,departmentName)
                .last("limit 1");
        Department department1 = departmentMapper.selectOne(departmentWrapper);
        if (department1 == null) {
            return Results.fail(ErrorCode.DEPARTMENT_NOT_EXIST.getCode(),ErrorCode.DEPARTMENT_NOT_EXIST.getMsg());
        } else {
            DepartmentVo departmentVo = new DepartmentVo();
            BeanUtils.copyProperties(department1,departmentVo);
            LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
            List<SysUser> sysUsers = sysUserMapper.selectList(sysUserWrapper);
            int count = 0;
            ArrayList<String> list = new ArrayList<>();
            for (SysUser sysUser : sysUsers) {
                if (sysUser.getDepartmentId().equals(department1.getDepartmentId())) {
                    count++;
                    list.add(sysUser.getUserName());
                }
            }
            departmentVo.setSysUserNumber(count);
            departmentVo.setSysUserNames(list);
            return Results.success(departmentVo);
        }
    }

    @Override
    @Transactional
    public Results departmentSelectList() {
        LambdaQueryWrapper<Department> departmentWrapper = new LambdaQueryWrapper<>();
        List<Department> departments = departmentMapper.selectList(departmentWrapper);
        if (departments == null) {
            return Results.success("部门信息为空!");
        }
        ArrayList<DepartmentVo> departmentVos = new ArrayList<>();
        for (Department department : departments) {
            DepartmentVo departmentVo = new DepartmentVo();
            BeanUtils.copyProperties(department,departmentVo);
            LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
            List<SysUser> sysUsers = sysUserMapper.selectList(sysUserWrapper);
            int count = 0;
            ArrayList<String> list = new ArrayList<>();
            for (SysUser sysUser : sysUsers) {
                if (sysUser.getDepartmentId().equals(department.getDepartmentId())) {
                    count++;
                    list.add(sysUser.getUserName());
                }
            }
            departmentVo.setSysUserNumber(count);
            departmentVo.setSysUserNames(list);
            departmentVos.add(departmentVo);
        }
        return Results.success(departmentVos);
    }

    @Override
    @Transactional
    public void departmentExport(HttpServletResponse response) {
        try {
            String fileName = URLEncoder.encode("部门信息.xlsx", "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            //设置类型，扩展名为.xls
            response.setContentType("application/vnd.ms-excel");
            ServletOutputStream out = response.getOutputStream();
            EasyExcel.write(out, DepartmentDataExcel.class).sheet("sheet1").doWrite(getData());
            response.flushBuffer();
//            return Results.success("数据导出成功！");
        } catch (Exception e) {
            e.printStackTrace();
//            return Results.fail(1038,"数据导出失败！");
        }

    }

    //创建方法返回list集合
    private List<DepartmentDataExcel> getData() {
        LambdaQueryWrapper<Department> departmentWrapper = new LambdaQueryWrapper<>();
        List<Department> departments = departmentMapper.selectList(departmentWrapper);
        ArrayList<DepartmentVo> departmentVos = new ArrayList<>();
        for (Department department : departments) {
            DepartmentVo departmentVo = new DepartmentVo();
            BeanUtils.copyProperties(department,departmentVo);
            LambdaQueryWrapper<SysUser> sysUserWrapper = new LambdaQueryWrapper<>();
            List<SysUser> sysUsers = sysUserMapper.selectList(sysUserWrapper);
            int count = 0;
            ArrayList<String> list = new ArrayList<>();
            for (SysUser sysUser : sysUsers) {
                if (sysUser.getDepartmentId().equals(department.getDepartmentId())) {
                    count++;
                    list.add(sysUser.getUserName());
                }
            }
            departmentVo.setSysUserNumber(count);
            departmentVo.setSysUserNames(list);
            departmentVos.add(departmentVo);
        }
        List<DepartmentDataExcel> list = new ArrayList<>();

        for (DepartmentVo departmentVo : departmentVos) {
            DepartmentDataExcel dataExcel = new DepartmentDataExcel();
            dataExcel.setDepartmentName(departmentVo.getDepartmentName());
            dataExcel.setDepartmentResponsibleContent(departmentVo.getDepartmentResponsibleContent());
            dataExcel.setSysUserNumber(departmentVo.getSysUserNumber());
//            dataExcel.setSysUserNames(departmentVo.getSysUserNames());
            list.add(dataExcel);
        }
        return list;
    }
}
